﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GDoc.Data;

namespace GDoc.Domain.Services
{
    public class AccountService
    {
        public UserRoleInAccount CreateAccount(string accountName, User owner)
        {
            IAccountRepository accountRepository = RepositoryFactory.CreateAccountRepository();
            IUserRoleInAccountRepository userRoleRepository = RepositoryFactory.CreateUserRoleInAccountRepository();

            Account account = new Account
            {
                Name = accountName
            };


            accountRepository.SaveOrUpdate(account);

            UserRoleInAccount userRole = new UserRoleInAccount
            {
                User = owner,
                Account = account,
                Role = RoleEnum.Owner
            };

            account.Users.Add(userRole);
            owner.Accounts.Add(userRole);

            userRoleRepository.SaveOrUpdate(userRole);

            return userRole;
        }

        public Account GetById(long accountId)
        {
            IAccountRepository repository = RepositoryFactory.CreateAccountRepository();

            return repository.GetById(accountId);
        }

        public IQueryable<Account> GetAll()
        {
            IAccountRepository repository = RepositoryFactory.CreateAccountRepository();

            return repository.GetAll();
        }

        public void Delete(Account account, User user)
        {
            IAccountRepository accounts = RepositoryFactory.CreateAccountRepository();
            IUserRoleInAccountRepository roles = RepositoryFactory.CreateUserRoleInAccountRepository();

            if (!account.IsOwner(user))
                throw new InvalidOperationException("Only the owner can delete the account.");

            var rolesToRemove = new List<UserRoleInAccount>(account.Users);

            foreach (var role in rolesToRemove)
                roles.Remove(role);

            accounts.Remove(account);
        }
    }
}
